import React, { use, useEffect, useRef, useState } from 'react';
import KLineChart from './KLineChart.jsx';
import TickChart from './TickChart.jsx';
import './StockChart.css';

//组件的接口使用的是后端的数据结构，然后传送到这里自己分解成echarts的数据结构，再进行渲染
const TickKlineChart = ({tickData,dayKdata,weekKdata,monthKdata,infoData}) => {
  const mainChartInstance = useRef(null);
  const [currentChartType, setCurrentChartType] = useState('1day');
  const [dayKData, setDayKData] = useState(null);
  const [weekKData, setWeekKData] = useState(null);
  const [monthKData, setMonthKData] = useState(null);
  const [showTickChart, setShowTickChart] = useState(true);
  const [stockInfo, setStockInfo] = useState({
    ts_code: '-' ,
    name: '-' ,
    close: '-' ,
    pct_chg: 0,
    amount: 0,
    turnover_rate_f: 0,
    volume_ratio: 0,
    circ_mv: 0,
    float_share: 0,
    total_mv: 0,
    total_share: 0,
    industry: '-' ,
    area: '-' ,
    is_hs:'-' ,
    pe:0,
    pb:0,
    dv_ratio:0,
  });

  useEffect(() => {
    // 根据当前图表类型决定是否显示 TickChart
    setShowTickChart(currentChartType === '1day' || currentChartType === '5day');
  }, [currentChartType]);
  
  // 窗口大小变化时，重新调整图表大小
  useEffect(() => {
    const handleResize = () => {
      if (mainChartInstance.current) {
        mainChartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  useEffect(() => {
    if(dayKdata && dayKdata.dates && dayKdata.dates.length > 0)
    {
      setDayKData(dayKdata)
    }
  },[dayKdata])

  useEffect(() => {
    if(weekKdata && weekKdata.dates && weekKdata.dates.length > 0)
    {
      setWeekKData(weekKdata)
    }
  },[weekKdata])

  useEffect(() => {
    if(monthKdata && monthKdata.dates && monthKdata.dates.length > 0)
    {
      setMonthKData(monthKdata)
    }
  },[monthKdata])

  // 确保 infoData 变化时更新右侧信息区域的数据
  useEffect(() => {
    if (infoData) {
      const formattedData = {
        ...infoData,
        pct_chg: `${(infoData.pct_chg).toFixed(2)}%`,
        amount: (infoData.amount / 100000).toFixed(1) + '亿元',
        turnover_rate_f: `${(infoData.turnover_rate_f).toFixed(2)}%`,
        volume_ratio: `${(infoData.volume_ratio).toFixed(2)}`,
        circ_mv: (infoData.circ_mv / 10000).toFixed(1) + '亿',
        total_mv: (infoData.total_mv / 10000).toFixed(1) + '亿',
        is_hs: infoData.is_hs === 'N' ? '否' : infoData.is_hs === 'H' ? '沪股通' : '深股通',
        pe: (infoData.pe).toFixed(2),
        pb: (infoData.pb).toFixed(2),
        dv_ratio: (infoData.dv_ratio).toFixed(2),
      };
      setStockInfo(formattedData);
    }
  }, [infoData]);


    // 图表类型按钮
  const chartTypeButtons = [
    { key: '1day', label: '分时' },
    { key: '5day', label: '5日' },
    { key: 'day', label: '日K' },
    { key: 'week', label: '周K' },
    { key: 'month', label: '月K' }
  ];
  return (
    <div className="main-container">
      <div className="stock-container">
        <div className="chart-tabs">
          {chartTypeButtons.map(button => (
            <button
              key={button.key}
              className={`tab-btn ${currentChartType === button.key ? 'active' : ''}`}
              onClick={() => {
                setCurrentChartType(button.key);
              }}
            >
              {button.label}
            </button>
          ))}
        </div>

        <div className="chart-main">
          {showTickChart ? (
            <TickChart tickData={tickData} currentChartType={currentChartType} />
          ) : (
            <KLineChart 
              data={currentChartType === 'day' ? dayKData : currentChartType === 'week' ? weekKData : monthKData} 
              symbol={stockInfo.ts_code}
            />
          )}
        </div> 
      </div>
    
     {/* 右侧信息区域 */}
     <div className="stock-info-panel">
      <div className="stock-info-item">名称: {stockInfo.name}</div>
       <div className="stock-info-item">代码: {stockInfo.ts_code}</div>
       <div className="stock-info-item">最新: {stockInfo.close}</div>
       <div className="stock-info-item">涨幅: {stockInfo.pct_chg}</div>
       <div className="stock-info-item">成交额: {stockInfo.amount}</div>
       <div className="stock-info-item">换手率: {stockInfo.turnover_rate_f}</div>
       <div className="stock-info-item">量比: {stockInfo.volume_ratio}</div>
       <div className="stock-info-item">流通市值: {stockInfo.circ_mv}</div>
       <div className="stock-info-item">总市值: {stockInfo.total_mv}</div>
       <div className="stock-info-item">行业: {stockInfo.industry}</div>
       <div className="stock-info-item">地域: {stockInfo.area}</div>
       <div className="stock-info-item">沪深股通: {stockInfo.is_hs}</div>
       <div className="stock-info-item">市盈率: {stockInfo.pe}</div>
       <div className="stock-info-item">市净率: {stockInfo.pb}</div>
       <div className="stock-info-item">股息率: {stockInfo.dv_ratio}</div>
     </div>
   </div>        
  );
};

export default TickKlineChart;